package com.magist.manage.util;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.magist.core.util.EmojiUtils;

import java.lang.reflect.Type;
import java.util.Date;

public class GsonBuilderUtils {

    public static Gson create() {

        GsonBuilder gb = new GsonBuilder();
//        gb.registerTypeAdapter(Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
//        gb.registerTypeAdapter(Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);

        gb.registerTypeAdapter(String.class, new EmojiSerializer());
        gb.registerTypeAdapter(String.class, new EmojiDeserializer());

        gb = gb
        //.serializeNulls()// 序列化null
        .setDateFormat("yyyy-MM-dd HH:mm:ss")// 设置日期时间格式
        //.setPrettyPrinting()// 格式化输出 json 数据
        ;

        Gson gson = gb.create();

        return gson;
    }

}

/* *********************** 把时间转成最原始的Long型. Gson默认的是不支持的, 需要手动处理一下. *********************** */

class DateSerializer implements JsonSerializer<Date> {

    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.getTime());
    }

}

class DateDeserializer implements JsonDeserializer<Date> {

    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {

        return new Date(json.getAsJsonPrimitive().getAsLong());
    }

}

/* ********************************************* Emoji 表情转化. ********************************************* */

class EmojiSerializer implements JsonSerializer<String> {

    public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(EmojiUtils.toUnicode(src));
    }

}

class EmojiDeserializer implements JsonDeserializer<String> {

    public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {

        return EmojiUtils.toAliases(json.getAsString());
    }

}
